//
//  SYLoginView.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2020/8/21.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import SnapKit

class SYLoginView: UIView {
    
    let minUsernameLength = 5
    let maxUsernameLength = 10
    let minPasswordLength = 5
    let maxPasswordLength = 16
    let disposBag = DisposeBag()
    var loginProtocol: SYLoginProtocol!
    var viewController: UIViewController!
    
    var bgView: UIImageView = {
        let img = UIImageView()
        img.image = UIImage(named: "bgtf")
        img.isUserInteractionEnabled = true
        
        return img
        
    }()
    
    
    
    var labTitle: UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor(hex: 0x333333)
        lb.font = UIFont.init(name: "PingFang-SC-Medium", size: 22)
        lb.text = "叁拾叁传感器管理平台"
        return lb
        
    }()
    
    var userView: UIView = {
       
        let v = UIView()
        v.layer.borderColor = UIColor(hex: 0x0072FF).cgColor
        v.layer.borderWidth = 0.5
        v.layer.cornerRadius = 22
        return v
        
    }()
    
    var passwordView: UIView = {
       
        let v = UIView()
        v.layer.borderColor = UIColor(hex: 0x0072FF).cgColor
        v.layer.borderWidth = 0.5
        v.layer.cornerRadius = 22
        return v
    }()
    
    var usernameTF: UITextField = {
        let tf = UITextField()
        tf.font = UIFont.systemFont(ofSize: 14)
        tf.textColor = .black
        tf.placeholder = "用户名/邮箱"
        return tf
    }()
    var usernameLB: UILabel = {
        let lb = UILabel()
        lb.textColor = .red
        lb.font = UIFont.systemFont(ofSize: 12)
//        lb.text = "用户名必须是5-10位的"
        return lb
    }()
    var passwordTF: UITextField = {
        let tf = UITextField()
        tf.font = UIFont.systemFont(ofSize: 14)
        tf.textColor = .black
        tf.isSecureTextEntry = true
        tf.placeholder = "密码"
        return tf
    }()
    var passwordLB: UILabel = {
        let lb = UILabel()
        lb.textColor = .red
        lb.font = UIFont.systemFont(ofSize: 12)
//        lb.text = "密码必须是5-16位的"
        return lb
    }()
    var passwordeyeBtn: UIButton = {
        let b = UIButton()
        b.setImage(UIImage(named: "login_eye"), for:.normal)
        
        return b
    }()
    
    var loginButton: UIButton = {
        let v = UIButton()
//        v.backgroundColor = UIColor.white
        v.setBackgroundImage(UIImage(named: "login_btnbg"), for: .normal)

        v.layer.cornerRadius = 22.5
        v.layer.masksToBounds = true
//        v.titleLabel?.font = UIFont.boldSystemFont(ofSize: 19)
        v.titleLabel?.font = UIFont.init(name: "PingFang-SC-Medium", size: 19)
//        v.setTitleColor(UIColor.init(hex: 0x39CA8C), for: .normal)
        v.setTitleColor(UIColor.init(hex: 0xffffff), for: .normal)
        v.setTitle("登录", for: .normal)
        return v
    }()
    var registerButton: UIButton = {
        let bt = UIButton()
        bt.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        bt.setTitle("注册", for: .normal)
        bt.setTitleColor(UIColor.white, for: .normal)
        bt.isHidden = true
        
        return bt
    }()
    var verifiCodeButton: UIButton = {
        let bt = UIButton()
        bt.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        bt.setTitle("验证码登录", for: .normal)
        bt.setTitleColor(UIColor.white, for: .normal)
        bt.isHidden = true

        return bt
    }()
    var bgImgView: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(named: "login_bg")
        v.isUserInteractionEnabled = true
        return v
    }()
    var logoImgView: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(named: "login_topicon")
        return v
    }()
    var accountImgView: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(named: "login_account")
        return v
    }()
    var passwordImgView: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(named: "login_password")
        return v
    }()
    var accountSepView: UIView = {
        let v = UIView()
//        v.backgroundColor = UIColor.init(hex: 0xCBFFEC)
        return v
    }()
    var passwordSepView: UIView = {
        let v = UIView()
//        v.backgroundColor = UIColor.init(hex: 0xCBFFEC)
        return v
    }()

    
    var backBtn: UIButton = {
        let v = UIButton()
        v.setImage(UIImage(named: "nav_back"), for: .normal)
        return v
    }()
    
    
    init(frame: CGRect, loginProtocol: SYLoginProtocol, viewController: UIViewController) {
        super.init(frame: frame)
        self.loginProtocol = loginProtocol
        self.viewController = viewController
        initViews()
        events()
        plugs()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initViews() {
        
        
        
        self.addSubview(bgImgView)
        self.bgImgView.addSubview(bgView)
        
        self.bgView.addSubview(logoImgView)
        self.bgView.addSubview(labTitle)
        self.bgView.addSubview(userView)
        self.bgView.addSubview(passwordView)
        self.bgView.addSubview(loginButton)
        
        self.userView.addSubview(usernameTF)
        self.userView.addSubview(accountImgView)
        self.userView.addSubview(usernameLB)
        
        self.passwordView.addSubview(passwordTF)
        self.passwordView.addSubview(passwordLB)
        self.passwordView.addSubview(passwordImgView)
        self.passwordView.addSubview(passwordeyeBtn)

        self.bgView.addSubview(accountSepView)
        self.bgView.addSubview(registerButton)
        self.bgView.addSubview(passwordSepView)
        self.bgView.addSubview(verifiCodeButton)

        passwordeyeBtn.addAction{[weak self] in
            if let `self` = self {
                

                self.passwordeyeBtn.isSelected = !self.passwordeyeBtn.isSelected
                
                self.passwordTF.isSecureTextEntry = !self.passwordeyeBtn.isSelected
                

            }
        }
        
//
        
        bgImgView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        bgView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-(BOTTOM_SAFE_HEIGHT+22))
            make.left.equalToSuperview().offset(7)
            make.right.equalToSuperview().offset(-7)
//            make.height.equalTo(368)
        }
        

        logoImgView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset (20)
            make.centerX.equalToSuperview()
            make.width.equalTo(29)
            make.height.equalTo(45)
        }
        
        
        labTitle.snp.makeConstraints { (make) in
            make.top.equalTo(self.logoImgView.snp.bottom).offset(17)
            make.centerX.equalToSuperview()
            make.height.equalTo(22)
        }
      
        userView.snp.makeConstraints { (make) in
            make.top.equalTo(self.labTitle.snp.bottom).offset(26)
            make.right.equalToSuperview().offset(-36)
            make.left.equalToSuperview().offset(36)
            make.height.equalTo(44)
        }
        
        passwordView.snp.makeConstraints { (make) in
            
            make.top.equalTo(self.userView.snp.bottom).offset(15)
            make.right.equalToSuperview().offset(-36)
            make.left.equalToSuperview().offset(36)
            make.height.equalTo(44)
            
        }
        
        accountImgView.snp.makeConstraints { (make) in
//            make.top.equalTo(self.userView.snp.top).offset(0)
            make.left.equalTo(self.userView.snp.left).offset(23)
            make.centerY.equalToSuperview()
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        
        passwordImgView.snp.makeConstraints { (make) in
//            make.top.equalTo(self.accountImgView.snp.bottom).offset(44)
            make.left.equalTo(self.accountImgView)
            make.centerY.equalToSuperview()
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        
        passwordeyeBtn.snp.makeConstraints { (make) in
            make.right.equalTo(self.passwordView.snp.right).offset(-23)
            make.centerY.equalToSuperview()
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        usernameTF.snp.makeConstraints { (make) in
            make.centerY.equalTo(self.accountImgView)
            make.left.equalTo(self.accountImgView.snp.right).offset(19)
            make.right.equalToSuperview().offset(-25)
            make.height.equalTo(25)
        }
        usernameLB.snp.makeConstraints { (make) in
            make.centerY.equalTo(self.accountImgView).offset(23)
            make.left.equalTo(self.accountImgView.snp.right).offset(19)
            make.right.equalToSuperview().offset(-25)
            make.height.equalTo(25)
        }
        accountSepView.snp.makeConstraints { (make) in
            make.top.equalTo(self.usernameTF.snp.bottom)
            make.left.right.equalTo(self.usernameTF)
            make.height.equalTo(LINE_HEIGHT)
        }
        passwordTF.snp.makeConstraints { (make) in
            make.centerY.equalTo(passwordImgView)
            make.left.equalTo(passwordImgView.snp.right).offset(19)
            make.right.equalToSuperview().offset(-25)
            make.height.equalTo(25)
        }
        passwordLB.snp.makeConstraints { (make) in
            make.centerY.equalTo(passwordImgView).offset(23)
            make.left.equalTo(passwordImgView.snp.right).offset(19)
            make.right.equalToSuperview().offset(-25)
            make.height.equalTo(25)
        }
        passwordSepView.snp.makeConstraints { (make) in
            make.top.equalTo(passwordTF.snp.bottom)
            make.left.right.equalTo(passwordTF)
            make.height.equalTo(LINE_HEIGHT)
        }
        loginButton.snp.makeConstraints { (make) in
            make.top.equalTo(passwordView.snp.bottom).offset(19)
//            make.left.equalToSuperview().offset(19)
//            make.right.equalToSuperview().offset(-29)
            make.centerX.equalToSuperview()
            make.height.equalTo(70)
            make.bottom.equalToSuperview().offset(-33)
        }
        registerButton.snp.makeConstraints { (make) in
            make.top.equalTo(loginButton.snp.bottom).offset(21)
            make.centerX.equalToSuperview()
            make.width.equalTo(150)
            make.height.equalTo(25)
        }
        verifiCodeButton.snp.makeConstraints { (make) in
            make.top.equalTo(registerButton.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
            make.width.equalTo(150)
            make.height.equalTo(25)
        }
  
    }
    
    func events() {
        /*
         *  .map负责对UITextField中的字符进行处理，判断字符长度，是否符合要求，将判断的值返回给usernameValid和passwordValid
         *
         *  shareReplay()是RxSwift提供的一个流操作函数，它是以重播的方式通知自己的订阅者，保证在观察者订阅这个流的时候始终都能回播最后N个，shareReplay(1)表示重播最后一个。
         *  shareReplay 会返回一个新的事件序列，它监听底层序列的事件，并且通知自己的订阅者们。 解决有多个订阅者的情况下，map会被执行多次的问题。
         */
        let usernameValid = usernameTF.rx.text
            .map { $0!.count >= self.minUsernameLength && $0!.count <= self.maxUsernameLength }
            .share(replay: 1)
        
        let passwordValid = passwordTF.rx.text
            .map { $0!.count >= self.minPasswordLength && $0!.count < self.maxPasswordLength }
            .share(replay: 1)
        
        let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { (usernameValid, passwordValid) -> Bool in
            usernameValid && passwordValid
        }
        
        // 或者
        //        let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 }
        //        .shareReplay(1)
        
        /*  绑定
         *  将usernameValid和passwordTF.rx_enabled绑定，即用usernameValid来控制passwordTF是否可以输入的状态
         *  bindTo就是RxSwfit中用来进行值绑定的函数
         */
        usernameValid
            .bind(to: passwordTF.rx.isEnabled) //username通过验证，passwordTF才可以输入
            .disposed(by: disposBag)
        
        usernameValid
            .bind(to: usernameLB.rx.isHidden)
            .disposed(by: disposBag)
        
        passwordValid
            .bind(to: passwordLB.rx.isHidden)
            .disposed(by: disposBag)
        
        everythingValid
            .bind(to: loginButton.rx.isEnabled) // 用户名密码都通过验证，才可以点击按钮
            .disposed(by: disposBag)
        
        loginButton.rx.tap //绑定button点击事件
            .subscribe(onNext: { [weak self] in
                if let `self` = self {
                    
                    self.loginProtocol.login(loginName: self.usernameTF.text ?? "", password:self.passwordTF.text ?? "")
                }
            })
            .disposed(by: disposBag)
        
        registerButton.rx.tap
            .subscribe(onNext: { [weak self] in
                let vc = SYRegisterViewController()
                self?.viewController.navigationController?.pushViewController(vc, animated: true)
            })
            .disposed(by: disposBag)
        
        verifiCodeButton.rx.tap
            .subscribe(onNext: { [weak self] in
                let vc = SYVerifiCodeLoginViewController()
                self?.viewController.navigationController?.pushViewController(vc, animated: true)
            })
            .disposed(by: disposBag)
        

        
//        self.loginProtocol.login(loginName: usernameTF.text ?? "", password: passwordTF.text ?? "")

    }
    
    func plugs() {
        switch loginProtocol.loginType {
        case .account:
            print("account")
        case .verifiCode:
            back()
            verifiCodeViews()
        case .register:
            back()
            registerViews()
        }
    }
    
    func back() {
        
        self.addSubview(backBtn)
        backBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(STATUSBAR_HEIGHT + 20)
            make.left.equalToSuperview().offset(30)
        }
        
        backBtn.rx.tap
            .subscribe(onNext: { [weak self] in
                self?.viewController.navigationController?.popViewController(animated: true)
            })
            .disposed(by: disposBag)
        
        registerButton.isHidden = true
        verifiCodeButton.isHidden = true

    }
}
